package com.younion.common.system;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

public class SystemConfig {
	private static final Logger logger = Logger.getLogger(SystemConfig.class);

	static private SystemConfig instance;

	Properties sysProps = null;

	InputStream is = null;

	FileOutputStream os = null;

	private String resourceURI = "/com/younion/conf/sysconf.properties";// 资源定位

	public void setResourceURI(String resourceURI) {
		this.resourceURI = resourceURI;
	}

	public SystemConfig() {
		this.init();
	}

	static synchronized public SystemConfig getInstance() {
		if (instance == null) {
			instance = new SystemConfig();
		}
		return instance;
	}

	public void init() {
		is = getClass().getResourceAsStream(resourceURI);
		sysProps = new Properties();
		try {
			sysProps.load(is);
		} catch (Exception e) {
			logger.error("不能读取属性文件:conf.properties");
			System.err.println("不能读取属性文件:conf.properties");
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception ee) {
					logger.error("Exception:" + ee);
					System.out.println("Exception : " + ee);
				}
			}
		}
	}

	public String getPropValue(String propertyName) {
		return getPropValue(propertyName, "");
	}

	/**
	 * 获取属性值
	 * 
	 * @param propertyName
	 *            --属性名
	 * @param defaultValue
	 *            --默认值
	 * @return
	 */
	public String getPropValue(String propertyName, String defaultValue) {

		if (sysProps != null) {
			return sysProps.getProperty(propertyName);

		}

		return defaultValue;
	}

	/**
	 * add by licq for logInterceptor
	 * 
	 * @return Properties
	 */
	public Properties getProperties() {
		return sysProps;
	}

	public void setProperties(Properties props) {
		this.sysProps = props;
	}

	/**
	 * add by liuliang 用于系统参数管理
	 * 
	 * @return Properties
	 */
	public void reload() {
		init();
	}

	public void setPropValue(String propertyName, String propertyValue) {
		if (sysProps != null) {
			sysProps.setProperty(propertyName, propertyValue);
		}
	}

	public void store(String comments) {
		if (sysProps != null) {
			try {
				String path = getClass().getResource(resourceURI).getPath();
				os = new FileOutputStream(path);
				sysProps.store(os, comments);
			} catch (FileNotFoundException e) {
				logger.error("FileNotFoundException:" + e);
			} catch (IOException e) {
				logger.error("IOException:" + e);
			} finally {
				if (os != null) {
					try {
						os.close();
					} catch (Exception ee) {
						logger.error("Exception:" + ee);
					}
				}
			}
		}
	}

}
